package xdu.lz.stage5_jucUtils.chapter4_semaphore;

import java.util.concurrent.Semaphore;

/**
 * Created at 2019/10/19 0019 下午 3:38
 * <p>
 * 信号量Semaphore:模拟限流锁
 */

public class SemaphoreLock {

    static class semaphoreLock {
        /**
         * 构造函数给的是permits个许可证，调用acquire后 permits-1，当permits = 0在调用acquire会阻塞
         * 调用release后permits会+1，所以可以实现锁，一次可让多个线程获得锁，这个锁就是许可证
         */
        private final Semaphore semaphore = new Semaphore(2);

        public void lock() throws InterruptedException {
            semaphore.acquire();
        }

        public void unlock() {
            semaphore.release();
        }
    }

    public static void main(String[] args) {
        semaphoreLock lock = new semaphoreLock();
        for (int i = 0; i < 4; i++) {
            new Thread(() -> {
                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " get the lock");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName() + " release the lock");
                }
            }, "t" + i).start();
        }
    }
}
